package com.qk.management.web.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author:Shuna
 * @Date: 2025/10/11 14:54
 * @Description:
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    private static final String TOKEN_HEADER_NAME = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (!ObjectUtil.isNotNull(token)) {
            log.info("token为空");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            log.info("token解析成功");
            String username = claims.get("username", String.class);
            log.info("用户名：{}", username);
            Integer userId = claims.get("id", Integer.class);
            log.info("用户id：{}", userId);
            CurrentUserContextHolders.set(userId);
            return true;
        } catch (Exception e) {
            log.error("token解析失败：{}", e.getMessage());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }
}
